from rest_framework import serializers
from drf_test.snippets.models import Snippets
from django.contrib.auth.models import User

# 1
"""
class SnippetSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    title = serializers.CharField(required=False, allow_blank=True, max_length=100)
    code = serializers.CharField(style={'base_template': "textarea.html"})
    linenos = serializers.BooleanField(required=False)
    language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python')
    style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly')

    def create(self, validated_data):
        # "
        # create and return a new 'Snippet' instance, given the validated data
        # :param validated_data:
        # :return:
        "
        return Snippets.objects.create(**validated_data)

    def update(self, instance, validated_data):
        # "
        # update and return existing `Snippet` instance, given the validated data
        # :param instance:
        # :param validated_data:
        # :return:
        # "
        # instance.title = validated_data.get("title", instance.title)
        # instance.code = validated_data.get("code", instance.code)
        # instance.linenos = validated_data.get("linenos", instance.linenos)
        # instance.language = validated_data.get("language", instance.language)
        # instance.style = validated_data.get("instance", instance.style)
        # 
        # instance.save()
        # return instance

# """


# 2
class SnippetSerilizer(serializers.ModelSerializer):
    owner = serializers.ReadOnlyField(source='owner.username')
    class Meta:
        model = Snippets
        fields = ['id', 'title', 'code', 'linenos', 'language', 'style', 'owner']


class UserSerializer(serializers.Serializer):
    snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippets.objects.all())

    class Meta:
        model = User
        fields = ["id", "username", "snippets"]

